package aip.core.dao.consultation;

import static org.springframework.util.Assert.hasText;

import java.util.Date;
import java.util.List;
import java.util.Set;

import org.springframework.dao.DataAccessException;

import com.googlecode.horncomb.bean.filter.ConditionSet;
import com.googlecode.horncomb.bean.filter.SimpleMapConditionSet;
import com.googlecode.horncomb.bean.order.Order;
import com.googlecode.horncomb.bean.paged.PagedList;
import com.googlecode.horncomb.orm.ibatis.SqlMapEntityDaoImpl;
import aip.core.model.consultation.Consultation;
import aip.ui.user.util.UserHelper;

/**
 * Consultation data access object
 * <p>
 * 负责人/principal:<br/>
 * 修改记录/revision:<br/>
 * 日期:<br/>
 * 修改人:<br/>
 * 修改说明:<br/>
 * @author
 * @version $Id$
 */
public class ConsultationDao extends SqlMapEntityDaoImpl<Consultation>
{

    private static final long serialVersionUID = -6953197821200229142L;

    /**
     * {@inheritDoc}
     */
    @Override
    public void insert(Consultation entity) throws DataAccessException
    {
        // TODO 当前用户
        entity.setEnterprise(UserHelper.getUser().getUsername());
        entity.setState(Consultation.STATE_TOASIGN);
        entity.setSubmitTime(new Date());
        super.insert(entity);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void update(Consultation entity) throws DataAccessException
    {
        Date now = new Date();
        if (Consultation.STATE_ASIGNED.equals(entity.getState())
                && entity.getReceiveTime() == null)
        {
            // TODO 当前用户
            entity.setCustomService(UserHelper.getUser().getUsername());
            entity.setReceiveTime(now);
        }
        else if (Consultation.STATE_REPLIED.equals(entity.getState())
                && entity.getReplyTime() == null)
        {
            entity.setReplyTime(now);
        }
        super.update(entity);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public PagedList<List<? extends Consultation>> query(
            ConditionSet constraints, Order order, int page, int pageSize)
            throws DataAccessException
    {
        return super.query(constraints, order, page, pageSize);
    }

    /**
     * 派发选中的咨询单
     * @param selectedIds
     */
    public void saveAssignByItems(Set<Integer> selectedIds, String expert)
    {
        // TODO Auto-generated method stub
        hasText(expert);
        ConditionSet cons = new SimpleMapConditionSet().addConstraint("ids",
                selectedIds.toArray(new Integer[] {})).addConstraint("expert",
                expert).addConstraint("customService",
                UserHelper.getUser().getUsername()).addConstraint(
                "receiveTime", new Date()).addConstraint("state",
                Consultation.STATE_ASIGNED);
        this.doUpdate(cons, null, "saveAssignByItems");
    }
}
